package com.xuecheng.learning.service.impl;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.learning.config.PayNotifyConfig;
import com.xuecheng.learning.model.po.ChooseCourse;
import com.xuecheng.learning.model.po.CourseTables;
import com.xuecheng.learning.service.ChooseCourseService;
import com.xuecheng.learning.service.CourseTablesService;
import com.xuecheng.messagesdk.model.po.MqMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 接收支付结果
 */
@Slf4j
@Service
public class ReceivePayNotifyService {
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    ChooseCourseService chooseCourseService;

    @Autowired
    CourseTablesService courseTablesService;

    @RabbitListener(queues = PayNotifyConfig.PAYNOTIFY_QUEUE)
    public void receive(Message message, Channel channel){
        try{
            Thread.sleep(5000);
        }catch(Exception e){
            throw new RuntimeException(e);
        }
//        String msg = new String(message.getBody());
//        MqMessage mqMessage = JSON.parseObject(msg,MqMessage.class);
        MqMessage mqMessage = JSON.parseObject(message.getBody(),MqMessage.class);
        log.info("学习中心服务接收支付结果：{}",mqMessage);
        //消息类型
        String messageType = mqMessage.getMessageType();
        //订单类型,60201表示购买课程
        String businessKey2 = mqMessage.getBusinessKey2();
        //这里只处理支付结果通知
        if (PayNotifyConfig.MESSAGE_TYPE.equals(messageType) && "60201".equals(businessKey2)) {
            Long chooseCourseId = Long.parseLong(mqMessage.getBusinessKey1());
            boolean b = courseTablesService.saveChooseCourseSuccess(chooseCourseId);
            if(!b){
                //添加选课失败，抛出异常，消息重回队列
                XueChengPlusException.cast("收到支付结果，添加选课失败");
            }
        }
    }
}
